package controller;

import java.io.IOException;
import java.util.Optional;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.DatabaseException;
/**
 * Servlet implementation class ViewController
 */
@WebServlet("/ViewController")
public class ViewController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String categoryName = new String(request.getParameter("category_name").getBytes(
                "iso-8859-1"), "UTF-8");
		System.out.println(categoryName);
		response.setContentType("text/html");
		if(categoryName!=null){
			try {
				Optional<Category> categoryOptional = Category.getCategory(categoryName,null,null,null,null,null, null,null);
				if(categoryOptional.isPresent()){
					Category category = categoryOptional.get();
					RequestDispatcher dispatcher = request.getRequestDispatcher("Category.jsp");
					request.setAttribute("category", category);
					dispatcher.forward(request, response);
				}else{
					response.sendRedirect("EmptyCategory.jsp");
				}
			} catch (DatabaseException e) {
				e.printStackTrace();
				response.sendRedirect("DatabaseProblem.jsp");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
